package com.kugou.miniapp.controller;

import com.kugou.miniapp.domain.LikeAndUserList;
import com.kugou.miniapp.domain.Music;
import com.kugou.miniapp.domain.Users;
import com.kugou.miniapp.service.MusicService;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.soap.SAAJResult;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class MusicController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    MusicService musicService;

    int num = 20;//一次请求返回多少数据

    //存放当前正在听歌的用户和音乐
    public static ConcurrentHashMap<String, LikeAndUserList> map_list = new ConcurrentHashMap<>();


    public static void removeItemFromMapListByUserId(String user_id){
        user_id = user_id.substring(0, 20);
        //查找之前已经在map_list的音乐， 并删除掉
        String remove_key = "uuu54覆盖35";
        Users u_remove = null;
        for (String mid: map_list.keySet()){
            LikeAndUserList likeAndUserList = map_list.get(mid);
            List<Users> users_list = likeAndUserList.getUser_list();
            for (int i = 0; i < users_list.size(); i++) {
                Users u = users_list.get(i);
                if (u.getUser_id().equals(user_id)){
                    u_remove = u;
                    if (users_list.size() == 1){
                        remove_key = mid;
                        break;
                    }
                }
            }
            if (u_remove != null){
                users_list.remove(u_remove);
            }
        }
        if (!remove_key.equals("uuu54覆盖35")){
            System.out.println("remove map_list's key:"+remove_key);
            map_list.remove(remove_key);
        }
    }

    @RequestMapping("get_his_music")
    public List<String> getHisMusic(String user_id){
        user_id = user_id.substring(0, 20);
        return musicService.getHisMusic(user_id);
    }

    @RequestMapping("get_like")
    public List<String> getLike(String user_id){
        user_id = user_id.substring(0, 20);
        return musicService.getLikeByUserId(user_id);
    }

    @RequestMapping("out")
    public int out(@RequestParam("user_id") String user_id){
        user_id = user_id.substring(0, 20);
        removeItemFromMapListByUserId(user_id);
        return 0;
    }

    @RequestMapping("like")
    public int like(@RequestParam("user_id")String user_id, @RequestParam("music_id")String music_id ){
        user_id = user_id.substring(0, 20);
        return musicService.like(user_id, music_id);
    }

    @RequestMapping("dis_like")
    public int disLike(@RequestParam("user_id")String user_id, @RequestParam("music_id")String music_id ) throws Exception {
        user_id = user_id.substring(0, 20);
        int count = musicService.disLike(user_id, music_id);
        if (count == 0){
            throw new Exception("删除失败， 不存在该记录");
        }
        return count;
    }

    @RequestMapping("del_his")
    public int delHis(@RequestParam("user_id")String user_id, @RequestParam("music_id")String music_id ) throws Exception {
        user_id = user_id.substring(0, 20);
        int count = musicService.delHis(user_id, music_id);
        if (count == 0){
            throw new Exception("删除失败， 不存在该记录");
        }
        return count;
    }

    //将map_list转换为list
    public List<LikeAndUserList> convertMapListToList(ConcurrentHashMap<String, LikeAndUserList> map_list, int count){
        List<LikeAndUserList> list = new ArrayList<>();
        for (String mid: map_list.keySet()){
            LikeAndUserList likeAndUserList = map_list.get(mid);
            list.add(likeAndUserList);
        }
        //根据第几次请求返回相应的数据
        //(count-1)*num   count*num-1
        int start = (count-1)*num;
        int end = count*num-1;
        int size = list.size();
        logger.info("count:"+count);
        if (start >= size){
            logger.info("start >= size start:"+start+" end:"+end);
            return null;
        }else if (end >= size){
            logger.info("end>=size start:"+start+" end:"+end);
            end = size-1;
        }
        logger.info("last  :  start:"+start+" end:"+end);
        if (list != null &&list.size()>0){
            System.out.print("map_list length:"+list.size());
        }else {
            logger.info("map_list now has't any Data");
        }

        return list.subList(start, end+1);
    }

    @PostMapping("get_cur_listen")
    public List<LikeAndUserList> getCurListen(Users user) throws Exception {
        if (user == null){
            throw new Exception("curent user obj is null："+user.toString());
        }else {
            logger.info("cur user is："+user.toString());
        }

        if(user.getCount() == 0){
            throw new Exception("count must more than 0，  cur count is："+user.getCount());
        }
        if (user.getUser_id() == null || user.getUser_id().equals("")){
            throw new Exception("user_id can't be null，now user_id is "+user.getUser_id());
        }
        user.setUser_id(user.getUser_id().substring(0, 20));
        for (String mid: map_list.keySet()){
            //判断map_list中的每首音乐对于user_id用户来说是否是喜欢
            map_list.get(mid).setIs_like(musicService.musicIsMyLike(user.getUser_id(), mid));
        }
        List<LikeAndUserList> list = convertMapListToList(map_list, user.getCount());
        return list==null||list.size()<=0?new ArrayList<>():list;
    }

    @RequestMapping("play_music")
    public int playMusic(Users user, @RequestParam("music_id")String music_id, @RequestParam("music_name")String music_name){
        user.setUser_id(user.getUser_id().substring(0, 20));
        //查找之前已经在map_list的音乐， 并删除掉
        removeItemFromMapListByUserId(user.getUser_id());
        //将mid和uid存放到历史听歌记录中
        musicService.addHisMusic(user.getUser_id(), music_id, music_name);

        //将自身听歌信息设置进map_list
        LikeAndUserList likeAndUserList = map_list.get(music_id);
        if (likeAndUserList==null){
            likeAndUserList = new LikeAndUserList();
            map_list.put(music_id, likeAndUserList);
        }
        likeAndUserList.setMusic_id(music_id);
        likeAndUserList.setMusic_name(music_name);
        likeAndUserList.getUser_list().add(user);
        return 1;
    }//playMusic end



}
